<template>
  <div 
    class="context-menu-item" 
    :class="{ 
      'danger': danger, 
      'disabled': disabled,
      'active': isActive
    }"
    @click="handleClick"
    @mouseover="handleMouseOver"
  >
    <el-icon v-if="icon" class="menu-icon">
      <component :is="icon" />
    </el-icon>
    <span class="menu-label">{{ label }}</span>
    <span v-if="shortcut" class="menu-shortcut">{{ shortcut }}</span>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, inject, ref, computed, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  label: {
    type: String,
    required: true
  },
  icon: {
    type: String,
    default: ''
  },
  command: {
    type: String,
    default: ''
  },
  danger: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  shortcut: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['click'])

// 注入菜单上下文
const contextMenu = inject('contextMenu', null)
const menuIndex = ref(-1)

// 判断当前项是否激活
const isActive = computed(() => {
  if (!contextMenu) return false
  return contextMenu.activeItemIndex.value === menuIndex.value
})

// 鼠标悬停时激活
const handleMouseOver = () => {
  if (contextMenu && !props.disabled) {
    contextMenu.activeItemIndex.value = menuIndex.value
  }
}

// 处理点击
const handleClick = (event) => {
  if (props.disabled) return
  
  emit('click', {
    command: props.command,
    event
  })
}

// 暴露点击方法给父组件
const click = () => {
  handleClick()
}

// 组件挂载时注册
onMounted(() => {
  if (contextMenu) {
    menuIndex.value = contextMenu.registerMenuItem({
      $el: null, // 将在nextTick后更新
      disabled: props.disabled,
      click
    })
  }
})

// 组件卸载时注销
onUnmounted(() => {
  if (contextMenu) {
    contextMenu.unregisterMenuItem({
      $el: null,
      disabled: props.disabled,
      click
    })
  }
})

// 暴露组件接口
defineExpose({
  click,
  disabled: props.disabled
})
</script>

<style scoped>
.context-menu-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  font-size: 13px;
  color: #374151;
  cursor: pointer;
  transition: background-color 0.15s ease;
  gap: 8px;
}

.context-menu-item:hover,
.context-menu-item.active {
  background-color: #f3f4f6;
}

.context-menu-item.danger {
  color: #dc2626;
}

.context-menu-item.danger:hover,
.context-menu-item.danger.active {
  background-color: #fef2f2;
}

.context-menu-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.context-menu-item.disabled:hover,
.context-menu-item.disabled.active {
  background-color: transparent;
}

.menu-icon {
  width: 16px;
  height: 16px;
  font-size: 14px;
  flex-shrink: 0;
}

.menu-label {
  flex: 1;
}

.menu-shortcut {
  color: #9ca3af;
  font-size: 11px;
  margin-left: 8px;
}
</style> 